<!--
 * @Description: 首页-调研明细页面
-->
<template>
  <div class="work-arrangement">
    <el-form ref="searchFormRef" :inline="true" :model="formData" class="work-arrangement-form" label-width="110px">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="调研日期:" prop="researchDate">
            <el-date-picker
              style="width: 100%"
              v-model="formData.researchDate"
              type="daterange"
              size="small"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :format=DEFAULT_DATE_FORMAT
              :valueFormat=DEFAULT_DATE_FORMAT
              @change="itineraryDateChange"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="带队领导:" prop="leadingUserName">
            <el-input
              v-model="formData.leadingUserName"
              size="small"
              readonly
              placeholder="请选择带队领导"
              @click.native="$refs.leadingTreeRef.show()"
            ></el-input>
          </el-form-item>
          <!-- 带队领导群组人员选择树 -->
          <jdf-group-identity-tree-transfer
            ref="leadingTreeRef"
            multiple
            group-code="DY_TJZ_COMPANY_LEADER"
            :identity-id="identityId"
            :expand-level="expandLevel"
            :defaultSelectedList="leadingTreeSelected"
            @select="(val) => selectIdentity(val, 'leadingUserName')"
          ></jdf-group-identity-tree-transfer>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调研对象:" prop="researchUnitName">
            <el-input
              v-model="formData.researchUnitName"
              size="small"
              readonly
              placeholder="请选择调研对象"
              @click.native="$refs.researchOrgTreeRef.show()"
            ></el-input>
          </el-form-item>
          <!-- 调研对象群组组织选择树 -->
          <jdf-group-org-tree-transfer
            ref="researchOrgTreeRef"
            :group-code="researchGroupCode"
            :identity-id="identityId"
            multiple
            :expand-level="expandLevel"
            :defaultSelectedList="researchOrgTreeSelected"
            @select="(val) => selectIdentity(val, 'researchUnitName')"
          ></jdf-group-org-tree-transfer>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="牵头部门:" prop="leadingDepartmentName">
            <el-input
              v-model="formData.leadingDepartmentName"
              size="small"
              readonly
              placeholder="请选择牵头部门"
              @click.native="$refs.leadingDepartOrgTreeRef.show()"
            ></el-input>
          </el-form-item>
          <!-- 牵头部门群组组织选择树 -->
          <jdf-group-org-tree-transfer
            ref="leadingDepartOrgTreeRef"
            group-code="DY_HOT_DEPT"
            :identity-id="identityId"
            multiple
            :expand-level="expandLevel"
            :defaultSelectedList="leadingDepartSelected"
            @select="(val) => selectIdentity(val, 'leadingDepartmentName')"
          ></jdf-group-org-tree-transfer>
        </el-col>
        <el-col :span="8">
          <el-form-item label="调研主题:" prop="researchSubject">
            <el-input v-model="formData.researchSubject" size="small" placeholder="请输入调研主题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态:" prop="approvalStatus">
            <el-select style="width: 100%" size="small" v-model="formData.approvalStatus" placeholder="请选择状态">
              <el-option
                v-for="( key, value ) in RESEARCH_DETAIL_STATUS"
                :key="key"
                :label="key"
                :value="value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="search-buttons">
      <el-button :loading="loading" size="small" type="primary" @click="getFormData">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <!-- TODO: 该版本暂时不展示以下按钮 先临时注释 -->
      <!--<el-button size="small" type="primary" @click="handleOpenDialog">录入</el-button>-->
      <!--<el-button size="small" type="primary">批量删除</el-button>-->
      <!--<el-button size="small" type="primary" @click="showQuarterlyPrintDialog = true">季度打印</el-button>-->
    </div>

    <el-button type="primary" @click="showSettingsDialog = true" size="small" style="margin-bottom: 10px">设置</el-button>
    <el-dialog title="列显示设置" :visible.sync="showSettingsDialog" width="30%">
      <div>
        <el-checkbox-group v-model="columnVisibility">
            <el-checkbox  v-for="(column, index) in columnsWithProp" :key="column.prop" :label="column.prop">
              <div class="sort-settings">
                {{ column.label }}
              <el-button-group>
                <el-button size="mini" type="primary" @click="moveColumn(index, 'up')" :disabled="index === 0" icon="el-icon-top">上移</el-button>
                <el-button size="mini" type="primary" @click="moveColumn(index, 'down')" :disabled="index === columnsWithProp.length - 1" icon="el-icon-bottom">下移</el-button>
              </el-button-group>
              </div>
            </el-checkbox>
        </el-checkbox-group>
      </div>
      <div slot="footer">
        <el-button @click="showSettingsDialog = false">取消</el-button>
        <el-button type="primary" @click="saveSettings">保存</el-button>
      </div>
    </el-dialog>
    <div class="table-container" v-loading="loading">
      <jdf-table
        :columns="visibleColumns"
        :data="tableData"
        :pagination-attrs="paginationAttrs"
        :pagination-events="detailsPaginationEvents"
        :table-events="detailsTableEvents"
      ></jdf-table>
    </div>

    <!-- 手动录入弹窗 -->
    <AddWorkArrangementDialog
      v-if="showAddDialog"
      :visible.sync="showAddDialog"
      @close="showAddDialog = false"
    />
    <!-- 季度打印对话框 -->
    <QuarterlyPrintDialog
      v-if="showQuarterlyPrintDialog"
      :visible.sync="showQuarterlyPrintDialog"
      @close="showQuarterlyPrintDialog = false"
    />
    <!-- 详情弹窗 -->
    <research-details-dialog
      v-if="showResearchDetailsDialog"
      :visible.sync="showResearchDetailsDialog"
      :allFieldsReadonly="true"
      :formData="detailsData"
      @close="showResearchDetailsDialog = false"
    />
  </div>
</template>

<script>
import listTableMixins from '@/mixins/listTableMixins';
import AddWorkArrangementDialog from './AddWorkArrangementDialog';
import QuarterlyPrintDialog from './QuarterlyPrintDialog';
import ResearchDetailsDialog from './ResearchDetailsDialog';
import { DEFAULT_DATE_FORMAT, PROVINCE_CODE, RESEARCH_DETAIL_STATUS } from '@/utils/constants';
import { message, messageTipConfirm, showErrorMsg } from '@/api/utils/pc-message';
import { getWorkList } from '@/api/business/subjectManage';
import { getStorageInfo } from '@/api/utils/storage-util';
import { get, map, chain, findIndex, concat, isEmpty } from 'lodash-es';

export default {
  name: 'WorkArrangement',
  mixins: [listTableMixins],
  components: {
    AddWorkArrangementDialog,
    QuarterlyPrintDialog,
    ResearchDetailsDialog
  },
  data() {
    return {
      DEFAULT_DATE_FORMAT,
      RESEARCH_DETAIL_STATUS,
      service: '',
      showAddDialog: false,
      showQuarterlyPrintDialog: false,
      // 调研明细弹窗状态
      showResearchDetailsDialog: false,
      // 详情数据
      detailsData: {},
      // 表单数据
      formData: {
        researchDate: [], // 调研日期
        leadingUserName: null, // 带队领导
        researchUnitName: null, // 调研对象
        leadingDepartmentName: '', // 牵头部门
        researchSubject: '', //调研主题
      },
      // 表单加载效果
      loading: false,
      // 表格数据
      tableData: [],
      // 固定列
      fixedColumn: [
        {
          type: 'selection',
          attrs: {
            align: 'center'
          }
        },
        {
          label: '序号',
          type: 'index',
          attrs: {
            index: index => this.startIndex + index,
            align: 'center'
          }
        },
      ],
      originalColumns: [
        {
          label: '调研起止日期',
          prop: 'researchDate',
          attrs: {
            minWidth: 80
          }
        },
        {
          label: '带队领导',
          prop: 'leadingUserName',
          attrs: {
            minWidth: 40
          }
        },
        {
          label: '调研对象',
          prop: 'researchUnitName',
          attrs: {
            minWidth: 40,
            'show-overflow-tooltip': true
          }
        },
        {
          label: '调研类型',
          prop: 'researchType',
          attrs: {
            minWidth: 40,
            'show-overflow-tooltip': true
          }
        },
        {
          label: '调研主题',
          prop: 'researchSubject',
          attrs: {
            'show-overflow-tooltip': true
          }
        },
        {
          label: '连带性规范性动作类型',
          prop: 'normativeType',
          attrs: {
            'show-overflow-tooltip': true
          }
        },
        {
          label: '带回解决问题数',
          prop: 'detectProblemNumber',
          attrs: {
            minWidth: 50,
            'show-overflow-tooltip': true
          }
        },
        {
          label: '解决问题数',
          prop: 'resolvedProblemNumber',
          attrs: {
            minWidth: 40,
            'show-overflow-tooltip': true
          }
        },
        {
          label: '状态',
          prop: 'approvalStatus',
          attrs: {
            minWidth: 30,
            formatter: (row, column, cellValue) => RESEARCH_DETAIL_STATUS[cellValue] || ''
          }
        },
      ],
      visibleColumns: [],
      showSettingsDialog: false,
      columnVisibility: [],
      multipleSelection: [],
      // 选人/组织选择树初始展示节点
      expandLevel: 1,
      // 带队领导群组人员已选择数据
      leadingTreeSelected: [],
      // 调研对象已选择的数据
      researchOrgTreeSelected: [],
      // 调研对象群组人员已选择数据
      leadingDepartSelected: [],
      // 默认可见字段
      defaultVisibleFields: [
        'researchDate', // 调研日期
        'leadingUserName', // 带队领导
        'researchUnitName', // 调研对象
        'researchType', // 牵头部门
        'researchSubject', // 调研主题
        'approvalStatus'   // 状态
      ],
      // 移动方向
      directionMovement: {
        up: -1, // 上移
        down: 1 // 下移
      }
    };
  },
  computed: {
    identityId() {
      return getStorageInfo('identityId');
    },

    // 明细表格事件
    detailsTableEvents() {
      return {
        'selection-change': this.handleSelectionChange,
        'row-click': this.rowClick,
      };
    },
    columnsWithProp() {
      return this.originalColumns.filter((column) => column.prop);
    },

    // 明细表格分页事件
    detailsPaginationEvents() {
      return {
        'current-change': this.pageChange,
        'size-change': this.sizeChange
      };
    },

    // 调研对象群组编码
    researchGroupCode() {
      // 获取省编码 如果为省公司则获取省公司群组字典 否则获取分公司群组字典
      return getStorageInfo('region') === PROVINCE_CODE ? 'DY_COMPANIES_FORM' : 'DY_HOT_DEPT'
    }
  },
  created() {
    this.initVisibleColumns();
    this.updateVisibleColumns();
    this.getFormData();
  },

  methods: {
    /**
     * 初始化可见列
     */
    initVisibleColumns() {
      const newFields = new Set(this.defaultVisibleFields);
      // 检查当前列的字段是否在新字段集合中，从而决定是否保留该列
      this.columnVisibility = this.originalColumns
        ?.map(item => item.prop) // 获取每一项的属性（prop）字段
        .filter(prop => newFields.has(prop)); // 过滤
    },

    /**
     * 获取表单数据
     */
    async getFormData() {
      this.loading = true;
      try {
        const { formData, pageNumber: page, pageSize: size } = this;
        const params = {
          ...formData,
          page,
          size,
          // 状态参数接收数组类型
          approvalStatus: formData.approvalStatus ? [formData.approvalStatus] : []
        };
        const { data: { data } } = await getWorkList(params);
        const { records, total } = data || {};
        Object.assign(this, {
          tableData: records?.map(({researchStartDate, researchEndDate, ...item }) => ({
            ...item,
            // 如果有开始时间 则拼接展示
            researchDate: researchStartDate ? `${researchStartDate} 至 ${researchEndDate}` : ''
          })),
          total
        });
      } catch (error) {
        showErrorMsg(error);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 重置表格数据
     */
    reset() {
      // 需要手动重置分页参数(默认回到第一页) 和 选人/组织树数据对应的id
      this.pageNumber = 1;
      this.initTreeData();
      this.formData = {
        leadingUserIds: [],
        researchUnitCodes: [],
        leadingDepartmentIds: []
      };
      this.getFormData();
    },

    /**
     * 初始化人员/群组选择树数据
     */
    initTreeData() {
      Object.assign(this, {
        leadingTreeSelected: [],
        researchOrgTreeSelected: [],
        leadingDepartSelected: []
      });
    },

    /**
     * 调研日期选择框值改变事件
     * @param value {Array} 调研日期
     */
    itineraryDateChange(value = []) {
      const [researchStartDate = '', researchEndDate = ''] = value;
      Object.assign(this.formData, {
        researchStartDate,
        researchEndDate
      });
    },

    /**
     * 表格行点击事件
     * @param row {Object} 当前行数据
     */
    rowClick(row) {
      // TODO 当前上线版本先不展示调研明细详情
      // Object.assign(this, {
      //   detailsData: row,
      //   showResearchDetailsDialog: true
      // });
    },

    /**
     * 多选框选中行改变事件
     * @param selectedRows {Array} 选中的行数据
     */
    handleSelectionChange(selectedRows) {
      this.multipleSelection = selectedRows;
    },

    /**
     * 切换分页
     * @param pageNumber {Number} 当前页码
     */
    pageChange(pageNumber) {
      this.pageNumber = pageNumber;
      this.getFormData();
    },

    /**
     * 切换每页条数
     * @param sizeNumber {Number} 每页条数
     */
    sizeChange(sizeNumber) {
      this.pageSize = sizeNumber;
      this.getFormData();
    },

    /**
     * 移动列位置
     * @param {number} index - 当前列索引
     * @param {string} direction - 移动方向 ('up' 或 'down')
     */
    moveColumn(index, direction) {
      const { directionMovement, columnsWithProp, $set, updateVisibleColumns } = this;
      // 获取移动方向
      const getMovement = directionMovement[direction];
      if (!getMovement) {
        return
      }

      // 获取新的索引
      const newIndex = index + getMovement;
      // 检查新索引是否超出范围
      if (newIndex < 0 || newIndex >= columnsWithProp.length) {
        return
      }

      // 使用数组解构交换位置
      [columnsWithProp[index], columnsWithProp[newIndex]] =
      [columnsWithProp[newIndex], columnsWithProp[index]];

      // 更新可见列
      $set(columnsWithProp, index, columnsWithProp[index]);
      $set(columnsWithProp, newIndex, columnsWithProp[newIndex]);
      updateVisibleColumns();
    },

    /**
     * 保存设置点击确定事件
     */
    saveSettings() {
      this.showSettingsDialog = false;
      this.updateVisibleColumns();
    },

    /**
     * 更新可见列
     */
    updateVisibleColumns() {
      const { originalColumns, columnVisibility, columnsWithProp, fixedColumn } = this;
      const visibilitySet = new Set(columnVisibility);

      const dynamicColumn = chain(originalColumns)
        // 过滤列 只保留prop存在于visibilitySet里可展示的列
        .filter(column => visibilitySet.has(column.prop))
        // 排序列 通过重新排序的索引进行升序排序
        .sortBy(column => findIndex(columnsWithProp, { prop: column.prop }))
        .value();
      // 合并固定列和动态列
      this.visibleColumns = concat(fixedColumn, dynamicColumn);
    },

    /**
     * 打开录入弹窗
     */
    handleOpenDialog() {
      this.showAddDialog = true;
    },

    /**
     * 批量删除
     */
    batchDeletion() {
      const { multipleSelection, getFormData } = this;
      if(isEmpty(multipleSelection)) {
        showErrorMsg('请选择要删除的数据！');
        return;
      }
      messageTipConfirm('确认要删除当前调研明细？', async () => {
        try {
          // FIXME: 这里后续调用批量删除接口
          message('删除成功！');
          getFormData();
        } catch (error) {
          showErrorMsg(error);
        }
      })
    },

    /**
     * 点击确定按钮将选中的数据回显到input中
     * @param data {Array} 选中的数据
     * @param echoField {String} 回显字段
     */
    selectIdentity(data, echoField) {
      // 类型到字段的映射配置
      const typeMapping = {
        // 牵头部门 查询参数: 人员需要的是 'loginName' 组织需要的是 'id'
        leadingUserName: {
          selectedField: 'leadingTreeSelected',
          idField: 'leadingUserIds',
          idMapper: (item) => get(item, 'userIdentityObj.loginName')
        },
        // 调研对象
        researchUnitName: {
          selectedField: 'researchOrgTreeSelected',
          idField: 'researchUnitCodes',
          idMapper: 'id'
        },
        // 牵头部门
        leadingDepartmentName: {
          selectedField: 'leadingDepartSelected',
          idField: 'leadingDepartmentIds',
          idMapper: 'id'
        }
      };
      // 获取当前类型的配置
      const config = typeMapping[echoField];
      if(!config) {
        return;
      }
      const { selectedField, idField, idMapper } = config;
      // 更新选中数据 方便再次打开时数据回显
      this[selectedField] = data;
      // 把当前选择的数据放到表单中用于查询和展示
      Object.assign(this.formData, {
        [echoField]: map(data, 'name').join(','),
        [idField]: map(data, idMapper)
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.work-arrangement {
  .el-form-item {
    display: flex;
    margin-right: 0;
    margin-bottom: 5px;
  }
  ::v-deep .el-form--inline .el-form-item__content {
    width: 100%;
  }
  ::v-deep .el-range-separator {
    width: 20px;
  }
  .search-buttons {
    margin: 10px 0;
    text-align: right;
  }
  .sort-settings {
    width: 350px;
    display: flex;
    justify-content: space-between;
    margin: 7px 0;
  }
}

</style>
